<template>
  <el-form
    :model="localFormData"
    label-width="auto"
    style="max-width: 650px"
    ref="ruleFormRef"
    :rules="rules"
    class=""
  >
    <el-row>
      <el-col :span="24">
        <h6 class="pb-3.5 text-gray-400 text-3.5">基础信息</h6>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="规格名称" prop="name" required>
          <el-input v-model="localFormData.name" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="商品分类" prop="category_id">
          <el-tree-select
            v-model="localFormData.category_id"
            :data="props.categorys"
            :render-after-expand="false"
            show-checkbox
            style="width: 190px"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="规格值" prop="values" class="mr-5">
          <div class="w-full">
            <el-button @click="addValue">添加</el-button>
            <div class="mt-2">
              <div
                v-for="(item, index) in specTypeOptions"
                :key="index"
                class="flex mb-1.5"
              >
                <el-input v-model="item.value" class="mr-2" />
                <el-button @click="removeValue(index)">删除</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="规格状态" prop="isActive">
          <el-switch v-model="isActive" @change="handleStatusChange" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="规格描述" prop="description">
          <el-input v-model="localFormData.description" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,  
  defineExpose,
  watchEffect,
  computed,
} from "vue";
import type { FormInstance } from "element-plus";
import * as Api from "@/api/index";
import { FormFactory } from "@/core/forms/form-factory";
import { SpecFormData } from "@/core/forms/spec-form";
import type { SpecItem, CategoryItem } from "@/api/types/product";

const props = defineProps<{
  formData: SpecItem;
  categorys: CategoryItem[];
  mode: "create" | "edit";
}>();

const ruleFormRef = ref<FormInstance>();
// 如果是编辑模式，初始化表单数据
const statusOptions = [
  { label: "已启用", value: "true" },
  { label: "已删除", value: "false" },
];
const localFormData = ref(FormFactory.create("spec") as SpecFormData); // 如果是编辑模式，初始化表单数据
console.log(localFormData);
const specTypeOptions = ref<{ label: string; value: string }[]>([]);
const rules = reactive({
  name: [
    { required: true, message: "请输入规格名称", trigger: "blur" },
    { min: 2, max: 30, message: "请输入2-30位规格名称", trigger: "blur" },
  ],
  status: [
    {
      required: true,
      message: "请选择是否启用",
      trigger: "change",
    },
  ],
  description: [{ required: false, message: "请输入规格描述", trigger: "blur" }],
  values: [
    {
      validator: (rule:any, value:any, callback:any) => {
        if (!specTypeOptions.value.length) {
          return callback(new Error("至少需要添加一个规格值"));
        }

        const hasEmpty = specTypeOptions.value.some((item) => !item.value?.trim());
        if (hasEmpty) {
          return callback(new Error("规格值不能为空"));
        }

        callback();
      },
      trigger: "blur", // 触发验证的时机
    },
  ],
});
// 暴露给父组件的异步提交方法
const submit = async () => {
  if (!ruleFormRef.value) return;

  return ruleFormRef.value
    .validate()
    .then(async (valid) => {
      if (!valid) return false;

      const submitFormData = localFormData.value.toSubmitData();

      try {
        console.log("提交表单数据:", submitFormData);
        console.log("提交表单数据:",JSON.stringify(submitFormData));
        const response =
          props.mode === "create"
            ? await Api.createSpecTypes(submitFormData)
            : await Api.updateSpecTypes(props.formData.id, submitFormData);
        return true;
      } catch (err) {
        throw err; // 会被外部的catch捕获
      }
    })
    .catch((err) => {
      console.error("错误:", err);
      return false;
    });
};
const addValue = () => {
  specTypeOptions.value.push({
    label: "",
    value: "",
  });
};
const removeValue = (index: number) => {
  specTypeOptions.value.splice(index, 1);
  // 删除后重新验证
  if (ruleFormRef.value) {
    ruleFormRef.value.validateField("values");
  }
};
const handleStatusChange = (value: boolean) => {};
const isActive = computed(() => {
  return localFormData.value.deleted_at;
});

// 自动响应props变化的智能初始化
watchEffect(() => {
  if (props.mode === "edit" && props.formData) {
    console.log("编辑模式，初始化表单数据", props.formData);
    localFormData.value = FormFactory.createFromExisting(
      "spec",
      props.formData
    ) as SpecFormData;
    // 初始化规格值
    if (props.formData.values) {
      specTypeOptions.value = props.formData.values.map((item:any) => ({
        label: item.toString(),
        value: item.toString(),
      }));
    }

  } else {
    localFormData.value = FormFactory.create("spec") as SpecFormData;
  }
});
defineExpose({ submit });
onMounted(() => {
  
});
</script>
<style scoped lang="scss">
.avatar-uploader .avatar[data-v-11e0307c] {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
